package edu.bluebeanforum.service.impl;

import edu.bluebeanforum.common.AppResult;
import edu.bluebeanforum.common.ResultCode;
import edu.bluebeanforum.exception.ApplicationException;
import edu.bluebeanforum.mapper.ArticleReplyMapper;
import edu.bluebeanforum.model.ArticleReply;
import edu.bluebeanforum.service.IArticleReplyService;
import edu.bluebeanforum.service.IArticleService;
import edu.bluebeanforum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private IArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        //参数校验
        if(articleReply==null||articleReply.getArticleId()==null
                || articleReply.getPostUserId()==null
                || StringUtil.isEmpty(articleReply.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALID.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALID));
        }
        //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date=new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row!=1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        //更新帖子表中的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("回复成功");
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //参数校验
        if(articleId==null||articleId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALID.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALID));
        }
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        return result;
    }
}
